import { ElMessage } from 'element-plus'
import { useTitle } from '@vueuse/core'

import router from '@/router/index'
import { useUserStore } from '@/stores'

/** 路由白名单 */
const ROUTES_WHITE = new Set(['/login'])

/** 默认系统名称 */
const defaultTitle = '志愿者管理平台'

router.beforeEach(async (to, from, next) => {
  useTitle(to.meta.title ?? defaultTitle)
  // next()
  // return
  // 白名单放行
  if (ROUTES_WHITE.has(to.path)) {
    next()
    return
  }

  try {
    const userStore = useUserStore()
    if (!userStore.user) {
      await userStore.getAndSetUser()
    }
  } catch (error) {
    ElMessage.error(error)
    next('/login')
    return
  }

  next()
})
